package com.github.tyc1210.aspect;

import com.github.tyc1210.config.CustomConnection;
import com.github.tyc1210.config.DynamicContextHolder;
import com.github.tyc1210.config.TransactionContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;


/**
 * 类描述
 *
 * @author tyc
 * @version 1.0
 * @date 2024-01-08 13:28:19
 */
@Aspect
@Component
public class MultiTransactionAspect {

    @Pointcut("@annotation(com.github.tyc1210.annotation.MultiTransaction) " +
            "|| @within(com.github.tyc1210.annotation.MultiTransaction)")
    public void multiTransactionPointCut() {

    }

    @Around("multiTransactionPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 开启事务
        TransactionContext.openTran();
        try {
            // 执行业务
            Object proceed = point.proceed();
            // 提交事务
            for (CustomConnection customConnection : DynamicContextHolder.MULTI_TRAN_CONNECTION.get()) {
                customConnection.commitMultiDbTran();
                customConnection.closeMultiDbTran();
            }
            return proceed;
        } catch (Throwable t) {
            // 回滚事务
            for (CustomConnection customConnection : DynamicContextHolder.MULTI_TRAN_CONNECTION.get()) {
                customConnection.rollBackMultiDbTran();
                customConnection.closeMultiDbTran();
            }
            throw t;
        } finally {
            // 清空 事务 连接，关闭当前事务
            DynamicContextHolder.MULTI_TRAN_CONNECTION.get().clear();
            TransactionContext.closeTran();
        }
    }
}
